package test00;

import test00.Student;
import java.lang.reflect.Field;


/**
 * 基于反射操作 - 体现反射的意义
 *
 *
 * @Author lzp
 * @Date 2024-03-27
 */
public class BeanUtil {

    /**
     *
     * 给任意对象任意属性设置值
     *
     * @param bean  任意对象
     * @param propertyName 任意属性
     * @param value 数据
     */

    public static void setProperty(Object bean,String propertyName,Object value) throws Exception {

        //stu.setName(value)
        //获取操作类的 Class 对象
        Class<?> clazz = bean.getClass();
        Field declaredField = clazz.getDeclaredField(propertyName);
        declaredField.setAccessible(true);
        declaredField.set(bean,value);

    }

    /**
     * 给任意对象任意属性设置值
     *
     * @param bean
     * @param propertyName
     * @return
     * @throws Exception
     */
    public static Object getProperty(Object bean,String propertyName) throws Exception {

        Class<?> aClass = bean.getClass();
        Field dField = aClass.getDeclaredField(propertyName);
        dField.setAccessible(true);
        return dField.get(bean);

    }

    /**
     *
     * 复制对象属性
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source,Object target) throws Exception {

        //获取源对象类的 Class 对象
        Class<?> sourceClass = source.getClass();

        //获取目标对象类的 Class 对象
        Class<?> targetClass = target.getClass();

        //获取目标对象的属性列表 - 循环遍历所有属性
        Field[] fields = sourceClass.getDeclaredFields();

        for (Field field : fields) {

            field.setAccessible(true);

            //获取源对象的属性名
            String fieldName = field.getName();
            //获取源对象的值
            Object value = field.get(source);
            //调用方法
            setProperty(target,fieldName,value);

        }


    }

    public static void main(String[] args) throws Exception {

        Student student = new Student();
        BeanUtil.setProperty(student, "name", "zuo");

        Object name = BeanUtil.getProperty(student, "name");
        System.out.println(name);

        Student stua = new Student("张三",18,99D);
        Student stub = new Student();

        BeanUtil.copyProperties(stua,stub);
        System.out.println(stub);

    }

}
